<?php
//+-----------------------------------------------------------
//| 人生是荒芜的旅行，冷暖自知，苦乐在心
//+-----------------------------------------------------------
//| Author:Janmas <janmas@126.com>
//+-----------------------------------------------------------
//| 
//+-----------------------------------------------------------


namespace app\common\plugins;


use app\common\exception\PluginNotFoundException;
use think\exception\ClassNotFoundException;
use think\exception\FuncNotFoundException;
use think\exception\HttpException;
use think\facade\Event;
use think\helper\Str;

class Route extends \think\Route
{
    /**
     * 插件路由请求
     * @param null $plugin
     * @param null $controller
     * @param null $action
     * @return mixed
     */
    public static function execute($plugin = null,$module='index', $controller = 'index', $action = 'index')
    {
        $app = app();
	    $app->http->name($plugin);
	    $request = $app->request;
        Event::trigger('plugin_begin', $request);
        if (empty($plugin) || empty($controller) || empty($action)) {
            throw new HttpException(500, lang('addon can not be empty'));
        }

        $request->plugin = $plugin;
        // 设置当前请求的控制器、操作
        $request->setController($controller)->setAction($action);

        /**
         * @var Plugin $pluginInstance
         */
        $pluginInstance = get_plugin_instance($plugin);
        // 获取插件基础信息
        $info = $pluginInstance->getInfo();
        if (!$info) {
            throw new PluginNotFoundException(sprintf('插件 %s 未找到 ',$plugin));
        }

        // 监听addon_module_init
        Event::trigger('plugin_module_init', $request);
        //TODO:检查是不是多模块
        $class = get_plugin_class($plugin, 'controller', $controller,$module);
	    if (!$class) {
	    	if($module == 'index'){
	    		$class = 'app\\plugins\\'.$plugin.'\\controller\\'. Str::studly($controller);
		    }else{
			    $class = 'app\\plugins\\'.$plugin.'\\'.$module.'\\controller\\'. Str::studly($controller);
		    }
            throw new ClassNotFoundException(sprintf('控制器 %s 未找到',$class));
        }
        // 生成控制器对象

	    $instance = new $class($app,$module);
        $vars = [];
        if (is_callable([$instance, $action])) {
            // 执行操作方法
            $call = [$instance, $action];
        } elseif (is_callable([$instance, '_empty'])) {
            // 空操作
            $call = [$instance, '_empty'];
            $vars = [$action];
        } else {
            // 操作不存在
            throw new FuncNotFoundException(sprintf('插件的方法 %s 未找到', get_class($instance).'->'.$action.'()'));
        }

        Event::trigger('plugin_action_begin', $call);

        return call_user_func_array($call, $vars);
    }
}